package com.atguigu.gmall.ums.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.ums.service.UserService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Map;


@Configuration
public class UmsListener {
//    @Autowired  //StringRedisTemplate和RedisTemplate不能混用
//    StringRedisTemplate redisTemplate;
    @Autowired
    UserService userService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    name = "pay.user.queue"
            ),
            exchange = @Exchange(
                    name = "pay.exchange",
                    type = ExchangeTypes.TOPIC,
                    ignoreDeclarationExceptions = "true"
            ),
            key = "pay.user.jifen"
    ))
    public void updateStockAndSales(Message message , Map<String,Object> map , Channel channel) throws IOException {
        try {
            String userId = map.get("userId").toString();
            String growth = map.get("growth").toString();
            String integration = map.get("integration").toString();
            //更新用户账户积分
            UserEntity userEntity = userService.getById(userId);
            userEntity.setGrowth(userEntity.getGrowth()+Integer.parseInt(growth));
            userEntity.setIntegration(userEntity.getIntegration()+Integer.parseInt(integration));
            userService.updateById(userEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),
                    false);
        } catch (Exception e) {
            e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                //丢弃消息： 可以给队列绑定死信队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                        false);
            }else{
                //第一次消费失败
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                        false,true);
            }
        }
    }

}
